#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <memory>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "Socket.hpp"
#include "Epoller.hpp"
#include "nocopy.hpp"
#include "Comm.hpp"

class Connection;
class TcpServer;
uint32_t EVENT_IN = (EPOLLIN | EPOLLET);
uint32_t EVENT_OUT = (EPOLLOUT | EPOLLET);
const int g_buffer_size = 128;
using func_t = std::function<void(std::shared_ptr<Connection>)>;
using except_func = std::function<void(std::weak_ptr<Connection>)>;

class Connection
{
public:
    Connection(int sock, std::weak_ptr<TcpServer> tcp_server_ptr)
        : _sock(sock),
          _tcp_server_ptr(tcp_server_ptr)
    {
    }
    void SetHandler(func_t revc_cb, func_t send_cb, except_func except_cb)
    {
        _recv_cb = revc_cb;
        _send_cb = send_cb;
        _except_cb = except_cb;
    }
    int SockFd()
    {
        return _sock;
    }
    void AppendInBuffer(const std::string &info)
    {
        _inbuffer += info;
    }
    void AppendOutBuffer(const std::string &info)
    {
        _outbuffer += info;
    }
    std::string &Inbuffer()
    {
        return _inbuffer;
    }
    std::string &Outbuffer()
    {
        return _outbuffer;
    }
    ~Connection()
    {
    }

private:
    int _sock;
    std::string _inbuffer; // 无法存放二进制
    std::string _outbuffer;

public:
    func_t _recv_cb;
    func_t _send_cb;
    except_func _except_cb;

    std::shared_ptr<TcpServer> _tcp_server_ptr;
    std::string _ip;
    uint16_t _port;
};

class TcpServer : public nocopy
{
    static const int num = 64;

public:
    TcpServer(uint16_t port, func_t OnMessage)
        : _port(port),
          _epoller_ptr(new Epoller()),
          _listensock_ptr(new Sock()),
          _quit(true),
          _OnMessage(OnMessage)
    {
    }
    void Init()
    {
        _listensock_ptr->Socket();
        SetNonBlock(_listensock_ptr->Fd());
        _listensock_ptr->Bind(_port);
        _listensock_ptr->Listen();
        lg(Info, "create listen socket success: %d", _listensock_ptr->Fd());
        AddConnection(_listensock_ptr->Fd(), EVENT_IN,
                      std::bind(&TcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);
    }
    void AddConnection(int sock, uint32_t event, func_t revc_cb, func_t send_cb, except_func except_cb, const std::string &ip = "0.0.0.0", const uint16_t &port = 0)
    {
        std::shared_ptr<Connection> new_connection = std::make_shared<Connection>(sock, std::shared_ptr<TcpServer>(this));
        new_connection->SetHandler(revc_cb, send_cb, except_cb);
        new_connection->_ip = ip;
        new_connection->_port = port;
        _connections.insert(std::make_pair(sock, new_connection));

        _epoller_ptr->Epollerctl(EPOLL_CTL_ADD, sock, event);
        lg(Debug, "add a new connection success, sockfd is: %d", sock);
    }
    void Accepter(std::shared_ptr<Connection> connection)
    {
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = ::accept(connection->SockFd(), (sockaddr *)&peer, &len);
            if (sock > 0)
            {
                uint16_t peerport = ntohs(peer.sin_port);
                char ipbuf[128];
                inet_ntop(AF_INET, &peer.sin_addr.s_addr, ipbuf, sizeof(ipbuf));
                // std::string peerip = ipbuf;
                lg(Debug, "get a new client, get info->[%s:%d], sockfd: %d", ipbuf, peerport, sock);

                SetNonBlock(sock);
                AddConnection(sock, EVENT_IN,
                              std::bind(&TcpServer::Recver, this, std::placeholders::_1),
                              std::bind(&TcpServer::Sender, this, std::placeholders::_1),
                              std::bind(&TcpServer::Excepter, this, std::placeholders::_1),
                              ipbuf, peerport);
            }
            else
            {
                if (errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                    break;
            }
        }
    }
    void Recver(std::shared_ptr<Connection> connection)
    {
        int sock = connection->SockFd();
        while (true)
        {
            char buffer[g_buffer_size];
            memset(buffer, 0, sizeof(buffer));
            ssize_t n = recv(sock, buffer, sizeof(buffer), 0);
            if (n > 0)
            {
                connection->AppendInBuffer(buffer);
                _OnMessage(connection);
            }
            else if (n == 0)
            {
                lg(Info, "sockfd: %d, client info %s:%d quit...", sock, connection->_ip.c_str(), connection->_port);
                connection->_except_cb(connection);
            }
            else
            {
                if (errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    lg(Warning, "sockfd: %d, client info %s:%d recv error...", sock, connection->_ip.c_str(), connection->_port);

                    connection->_except_cb(connection);
                    break;
                }
            }
        }

    }
    void Sender(std::shared_ptr<Connection> connection)
    {
        auto outbuffer = connection->Outbuffer();
        while (true)
        {


            ssize_t n = send(connection->SockFd(), outbuffer.c_str(), outbuffer.size(), 0);
            if (n > 0)
            {
                outbuffer.erase(0, n);
                if (outbuffer.empty())
                    break;
            }
            else if (n == 0)
            {
                return;
            }
            else
            {

                if (errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    lg(Warning, "sockfd: %d, client info %s:%d send error...", connection->SockFd(), connection->_ip.c_str(), connection->_port);
                    connection->_except_cb(connection);
                    return;
                }
            }
        }
        if (!outbuffer.empty())
        {
            EnableEvent(connection->SockFd(), true, true);
        }
        else
        {
            EnableEvent(connection->SockFd(), true, false);
        }
    }
    void EnableEvent(int sock, bool readable, bool writeable)
    {
        uint32_t events = 0;
        events |= (readable ? EVENT_IN : 0) | (writeable ? EVENT_OUT : 0);
        _epoller_ptr->Epollerctl(EPOLL_CTL_MOD, sock, events);
    }
    void Excepter(std::weak_ptr<Connection> connection)
    {
        if(connection.expired()) return;
        auto conn = connection.lock();
        lg(Warning, "Excepter hander sockfd: %d, client info %s:%d excepter handler", conn->SockFd(), conn->_ip.c_str(), conn->_port);
        _epoller_ptr->Epollerctl(EPOLL_CTL_DEL, conn->SockFd(), 0);
        lg(Debug, "close %d done...\n", conn->SockFd());
        close(conn->SockFd());
        lg(Debug, "remove %d from _connections...\n", conn->SockFd());
        //_connections[conn->SockFd()].reset();
        //_connections.erase(conn->SockFd());
    }
    bool IsConnectionSafe(int fd)
    {
        auto iter = _connections.find(fd);
        if (iter == _connections.end())
            return false;
        else
            return true;
    }
    void Dispatcher(int timeout)
    {

        int n = _epoller_ptr->EpollerWait(revs, num, timeout);
        for (int i = 0; i < n; i++)
        {
            uint32_t events = revs[i].events;
            int sock = revs[i].data.fd;
            if (events & EPOLLERR)
                events |= (EPOLLIN | EPOLLOUT);

            if (events & EPOLLHUP)
                events |= (EPOLLIN | EPOLLOUT);

            if ((events & EPOLLIN) && IsConnectionSafe(sock))
            {
                if (_connections[sock]->_recv_cb)
                    _connections[sock]->_recv_cb(_connections[sock]);
            }
            if ((events & EPOLLOUT) && IsConnectionSafe(sock))
            {
                if (_connections[sock]->_send_cb)
                    _connections[sock]->_send_cb(_connections[sock]);
            }
        }
        std::cout << "quit2" << std::endl;
    }
    void Loop()
    {
        _quit = false;

        while (!_quit)
        {
            Dispatcher(-1);

            PrintConnection();
        }
        _quit = true;
    }

    void PrintConnection()
    {
        std::cout << "_connections fd list: ";
        for (auto &connection : _connections)
        {
            std::cout << connection.second->SockFd() << ", ";
            std::cout << "inbuffer: " << connection.second->Inbuffer();
        }
        std::cout << std::endl;
    }
    ~TcpServer()
    {
        _listensock_ptr->Close();
    }

private:
    std::shared_ptr<Epoller> _epoller_ptr;
    std::shared_ptr<Sock> _listensock_ptr;
    std::unordered_map<int, std::shared_ptr<Connection>> _connections;
    struct epoll_event revs[num];
    uint16_t _port;
    bool _quit;
    func_t _OnMessage;
};